package com.motong.gongdan.controller.system;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.service.*;
import com.motong.gongdan.util.*;
import com.motong.gongdan.vo.resp.UserListByProcessIdVo;
import com.motong.gongdan.vo.system.UserController.query.UpdatePermissionQuery;
import com.motong.gongdan.vo.system.otherVo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Api(value = "用户", tags = {"用户相关"})
@RestController
@RequestMapping(value = "/sys/user/")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    SysMenuService sysMenuService;
    @Resource
    DepartmentsService departmentsService;
    @Resource
    UserMenuService userMenuService;
    @Resource
    FactoryService factoryService;
    @Resource
    CustomFieldService customFieldService;
    @Resource
    private ProcessesService processesService;

    @Resource
    private MissionService missionService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

//    @Resource
//    private DataSourceConfig dataSourceConfig;


    @ApiOperation(value = "用户列表")
    @UserLoginToken
    @RequestMapping(value = "user_list", method = RequestMethod.POST)
    public ResponseData userList(@RequestBody UserListVo vo) {
        IPage<User> page = userService.page(new Page<>(vo.getPage(), vo.getLimit()), new QueryWrapper<User>()
                .eq(StringUtil.isNotBlank(vo.getAccount()), "account", vo.getAccount())
                .like(StringUtil.isNotBlank(vo.getName()), "name", vo.getName())
                .like(vo.getRole() != null, "role", vo.getRole())
                .eq(vo.getState() != null, "state", vo.getState())
                .eq(vo.getVirtualType() != null, "virtual_type", vo.getVirtualType())
                .eq("factory_id", LoginUtil.getLoginUserFactory()));
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(u -> {
                if (u.getWebMenuId() != null) {
                    List<SysMenu> webList = sysMenuService.getBaseMapper().selectMenuByIdList(Arrays.asList(u.getWebMenuId().split(",")));
                    u.setWebMenu(webList);
                }
                if (u.getH5MenuId() != null) {
                    List<SysMenu> h5List = sysMenuService.getBaseMapper().selectMenuByIdList(Arrays.asList(u.getH5MenuId().split(",")));
                    u.setH5Menu(h5List);
                }
                u.setDepId("");
                List<Departments> depList = userService.getBaseMapper().getDepByUserId(u.getId().toString());
                if (!CollectionUtils.isEmpty(depList)) {
                    u.setDepName(depList.stream().map(d -> d.getName()).collect(Collectors.joining(",")));
                    u.setDepId(depList.stream().map(d -> d.getId().toString()).collect(Collectors.joining(",")));
                }
                u.setPassword("**********");
                if (StringUtil.isNotBlank(u.getOther())) {
                    u.setCustomFieldVos(customFieldService.handleCustomFieldForList(u.getOther()));
                }
            });
        }
        return ResponseData.success(page);
    }

    @ApiOperation(value = "用户操作")
    @UserLoginToken
    @RequestMapping(value = "user_handle", method = RequestMethod.POST)
    public ResponseData userHandle(@RequestBody User vo) {
        boolean isUpdate = Objects.nonNull(vo.getId());
        // 账号/手机号
        LambdaQueryWrapper<User> accountMobileRepeatQw = new LambdaQueryWrapper<User>().eq(User::getFactoryId, LoginUtil.getLoginUserFactory()).ne(isUpdate, User::getId, vo.getId());
        accountMobileRepeatQw.and(i -> i.eq(User::getAccount, vo.getAccount()).or().eq(StringUtils.hasLength(vo.getMobile()), User::getMobile, vo.getMobile()));
        long count = userService.count(accountMobileRepeatQw);
        if (count > 0) {
            return ResponseData.fail(500, "系统中已存在相同手机号的其他用户");
        }

        if (StringUtils.hasLength(vo.getMobile())) {
            LambdaQueryWrapper<User> mobileRepeatQw = new LambdaQueryWrapper<User>().ne(isUpdate, User::getId, vo.getId()).eq(User::getMobile, vo.getMobile());
            LoginUtil.setIgnoreFactory(true);
            long mobileCount = userService.count(mobileRepeatQw);
            LoginUtil.setIgnoreFactory(false);
            if (mobileCount > 0) {
                return ResponseData.fail(500, "系统中已存在相同手机号的其他用户");
            }
        }
        if (StringUtils.hasLength(vo.getName())) {
            accountMobileRepeatQw.clear();
            LambdaQueryWrapper<User> nameRepeatQW = accountMobileRepeatQw.eq(User::getFactoryId, LoginUtil.getLoginUserFactory()).ne(isUpdate, User::getId, vo.getId()).eq(StringUtils.hasLength(vo.getName()), User::getName, vo.getName());
            if (userService.count(nameRepeatQW) > 0) {
                return ResponseData.fail(500, "用户名称重复!");
            }
        }
        // 账号管理员判重
        if (StringUtils.hasLength(vo.getRole()) && vo.getRole().contains("0")) {
            LambdaQueryWrapper<User> roleRepeatQw = new LambdaQueryWrapper<User>().eq(User::getFactoryId, LoginUtil.getLoginUserFactory()).like(User::getRole, "0").ne(isUpdate, User::getId, vo.getId());
            if (userService.count(roleRepeatQw) > 0) {
                return ResponseData.fail(500, "用户账号管理员的角色已使用完");
            }
        }

        String pwd = MD5Util.getPwd(8);
        vo.setOther(CollectionUtils.isEmpty(vo.getCustomFieldVos()) ? "" : customFieldService.handleObjectCreateOrEdit(vo.getCustomFieldVos()).toJSONString());
        if (vo.getId() == null) {
            if (StringUtil.isBlank(vo.getPassword())) {
                vo.setPassword(MD5Util.generate(pwd));
                vo.setFactoryId(LoginUtil.getLoginUserFactory());
                vo.setCreateTime(new Date());
                vo.setUpdateTime(new Date());
                userService.saveOrUpdate(vo);
                if (StringUtil.isNotBlank(vo.getDepId())) {
                    Arrays.asList(vo.getDepId().split(",")).forEach(f -> {
                        Departments d = departmentsService.getById(Integer.valueOf(f));
                        d.setIds(StringUtil.isBlank(d.getIds()) ? vo.getId().toString() : d.getIds() + "," + vo.getId());
                        departmentsService.updateById(d);
                    });
                }
                //工序中添加新成员
                List<Processes> allPeopleProcesses = processesService.list(new LambdaQueryWrapper<Processes>().eq(Processes::getPermissionsName, "所有人"));
                if (!CollectionUtils.isEmpty(allPeopleProcesses)) {
                    allPeopleProcesses.forEach(i -> {
                        i.setPermissions(StringUtils.hasLength(i.getPermissions()) ? i.getPermissions().concat(",").concat(vo.getId().toString()) : vo.getId().toString());
                    });
                    processesService.updateBatchById(allPeopleProcesses);
                }
            }
        } else if (vo.getId() != null) {
            User u = userService.getById(vo.getId());

            if (StringUtils.hasLength(vo.getAccount()) && !vo.getAccount().equals(u.getAccount())) {
                RedisUtil.del("JWT-TOKEN-U" + u.getAccount());
            }
            vo.setUpdateTime(new Date());
            if (!u.getState().equals(vo.getState())) {
                redisTemplate.delete("motong:gongdan:login:ErrNum:" + vo.getId());
                redisTemplate.delete("motong:gongdan:login:cd:" + vo.getId());
            }
            //更新时名称替换
            if (StringUtils.hasLength(vo.getName()) && !vo.getName().equals(u.getName())) {
                List<Processes> oriProcessName = processesService.list(new LambdaQueryWrapper<Processes>().like(Processes::getPermissionsName, u.getName()));
                oriProcessName.forEach(i -> {
                    if (StringUtils.hasLength(i.getPermissionsName())) {
                        List<String> newPermissionName = new ArrayList<>();
                        for (String name : i.getPermissionsName().split(",")) {
                            newPermissionName.add(name.equals(u.getName()) ? vo.getName() : name);
                        }
                        if (!CollectionUtils.isEmpty(newPermissionName)) {
                            i.setPermissionsName(String.join(",", newPermissionName));
                        }

                    }
                });
                processesService.updateBatchById(oriProcessName);
            }
            userService.updateById(vo);
            if (Objects.nonNull(vo.getDepId())) {
                List<Departments> departments = departmentsService.list(new LambdaQueryWrapper<Departments>().like(Departments::getIds, vo.getId()));
                // 去除存在的所属部门
                departments.forEach(i -> {
                    if (StringUtils.hasLength(i.getIds())) {
                        Set<String> ids = Arrays.stream(i.getIds().split(",")).filter(d -> !d.equals(vo.getId().toString())).collect(Collectors.toSet());
                        i.setIds(String.join(",", ids));
                        i.setUpdateTime(new Date());
                    }
                });
                // 设置新部门
                if (StringUtils.hasLength(vo.getDepId())) {
                    Departments newDep = departmentsService.getById(vo.getDepId());
                    if (Objects.nonNull(newDep)) {
                        newDep.setIds(StringUtils.hasLength(newDep.getIds()) ? newDep.getIds().concat(",").concat(vo.getId().toString()) : vo.getId().toString());
                        departments.add(newDep);
                    }
                }
                if (!CollectionUtils.isEmpty(departments)) {
                    departmentsService.updateBatchById(departments);
                }
            }
        }
        UserMenu ownUserMenu = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", vo.getId()).eq("type", 0));
        UserMenu ownH5Menu = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", vo.getId()).eq("type", 1));
        if (ownH5Menu == null) {
            LoginUtil.setIgnoreFactory(true);
            UserMenu umLocal = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", 0).eq("type", 1));
            LoginUtil.removeIgnoreFactory();
            UserMenu um = new UserMenu();
            um.setUserId(vo.getId());
            um.setType(1);
            um.setMenu(umLocal.getMenu());
            userMenuService.save(um);
        }
        if (ownUserMenu == null) {
            LoginUtil.setIgnoreFactory(true);
            UserMenu umLocal = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", 0).eq("type", 0));
            LoginUtil.removeIgnoreFactory();
            UserMenu um = new UserMenu();
            um.setUserId(vo.getId());
            um.setType(0);
            um.setMenu(umLocal.getMenu());
            userMenuService.save(um);
        }
        Factory factory = factoryService.getById(LoginUtil.getLoginUserFactory());
        if (StringUtil.isNotBlank(pwd)) {
            return ResponseData.success(pwd);
        }

        return ResponseData.success("success");
    }

    @ApiOperation(value = "修改密码")
    @UserLoginToken
    @RequestMapping(value = "reset_pwd", method = RequestMethod.POST)
    public ResponseData resetPwd(@RequestBody ResetPwdVo vo) {
        if (vo.getId() != null) {
            User user = userService.getById(vo.getId());
            if (user != null) {
                if (!vo.getPwd().equals(vo.getConfirmPwd())) {
                    return ResponseData.fail(500, "密码校验错误");
                }
                user.setPassword(MD5Util.generate(vo.getPwd()));
                user.setUpdateTime(new Date());
                userService.updateById(user);
                RedisUtil.del("JWT-TOKEN-U" + user.getAccount());
                return ResponseData.success("success");
            }
        }
        return ResponseData.fail(500, "失败");
    }

    @ApiOperation(value = "导入")
    @UserLoginToken
    @RequestMapping(value = "excel_import", method = RequestMethod.POST)
    public ResponseData excelImport(MultipartFile file) throws IOException {
        userService.handleImport(file);
        return ResponseData.success("请查看导入日志");
    }


    @ApiOperation(value = "导出")
    @UserLoginToken
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public void export(String ids, HttpServletResponse response) throws IOException {
        if (StringUtil.isNotBlank(ids)) {
            List<String> idsList = Arrays.asList(ids.split(","));
            List<User> userList = userService.listByIds(idsList);
            if (!CollectionUtils.isEmpty(userList)) {
                List<UserExcelModel> modelList = new ArrayList<>();
                userList.forEach(u -> {
                    UserExcelModel uem = new UserExcelModel();
                    BeanUtils.copyProperties(u, uem);
                    modelList.add(uem);
                });
                String fileName = "exportExcel" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).sheet("用户导出数据").head(UserExcelModel.class).doWrite(modelList);
            }
        } else {

            List<User> userList = userService.list();
            if (!CollectionUtils.isEmpty(userList)) {
                List<UserExcelModel> modelList = new ArrayList<>();
                userList.forEach(u -> {
                    UserExcelModel uem = new UserExcelModel();
                    BeanUtils.copyProperties(u, uem);
                    modelList.add(uem);
                });
                String fileName = "exportExcel" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).sheet("用户导出数据").head(UserExcelModel.class).doWrite(modelList);
            }
        }
    }

    @ApiOperation(value = "编辑权限")
    @UserLoginToken
    @RequestMapping(value = "edit_permissions", method = RequestMethod.POST)
    public ResponseData editPermissions(@RequestBody PermissionsVo vo) {
        if (vo.getId() != null) {
            QueryWrapper<UserMenu> qw = new QueryWrapper<>();
            qw.eq("user_id", vo.getId()).eq("type", vo.getType());
            UserMenu userMenu = userMenuService.getOne(qw);

            if (!CollectionUtils.isEmpty(vo.getUpdatePermissionQueries())) {
                vo.getUpdatePermissionQueries().forEach(i -> {
                    cn.hutool.json.JSONArray jsonArray = JSONUtil.parseArray(vo.getMenuIds());
                    cn.hutool.json.JSONArray newMenu = this.updateUserMenu(jsonArray, i.getPermCode(), i.getPropertyName(), i.getPropertyValue());
                    vo.setMenuIds(JSONUtil.toJsonStr(newMenu));
                });
            }
            if (userMenu == null) {
                UserMenu menu = new UserMenu();
                menu.setUserId(vo.getId());
                menu.setMenu(vo.getMenuIds());
                menu.setType(vo.getType());
                userMenuService.save(menu);

            } else {
                //不为空就 修改
                userMenu.setMenu(vo.getMenuIds());
                userMenuService.updateById(userMenu);
            }


            return ResponseData.success(vo.getMenuIds());
        }
        return ResponseData.fail(500, "失败");
    }

    @UserLoginToken
    @ApiOperation(value = "权限列表")
    @ApiImplicitParam(paramType = "query", dataType = "int", name = "type", value = "web/移动端 0-web 1-移动端")
    @RequestMapping(value = "permissions_list", method = RequestMethod.GET)
    public ResponseData permissionsList(Integer type, Integer userId) {

        if (userId == null) {
            userId = LoginUtil.getLoginUserId();
        }
        UserMenu menu = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", userId).eq("type", type));
        if (menu != null) {
            return ResponseData.success(menu);
        }
        return ResponseData.fail(500, "SYSTEM ERROR");
    }


    @UserLoginToken
    @ApiOperation(value = "添加/编辑菜单----开发使用")
    @RequestMapping(value = "add_menu", method = RequestMethod.POST)
    public ResponseData addMenu(@RequestBody SysMenu vo) {
        sysMenuService.saveOrUpdate(vo);
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "部门列表")
    @RequestMapping(value = "dep_list", method = RequestMethod.POST)
    public ResponseData depList(@RequestBody NormalVo vo) {
        IPage<Departments> data = departmentsService.page(new Page<Departments>(vo.getPage(), vo.getLimit()),
                new QueryWrapper<Departments>()
                        .like(StringUtil.isNotBlank(vo.getCode()), "code", vo.getCode())
                        .like(StringUtil.isNotBlank(vo.getName()), "name", vo.getName()).eq("del_flag", 0).orderByDesc("id"));
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            data.getRecords().forEach(d -> {
                if (d.getCreatePerson() != null) {
                    User u = userService.getById(d.getCreatePerson());
                    d.setCreateName(u.getName());
                }
                if (d.getIds() != null) {
                    List<User> userList = userService.listByIds(Arrays.asList(d.getIds().split(",")));
                    if (!CollectionUtils.isEmpty(userList)) {
                        List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
                        d.setDepUsers(nameList);
                    }
                }
            });
        }
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "部门操作")
    @PostMapping("dep_handle")
    public ResponseData<?> depHandle(@RequestBody Departments vo) {
        Departments dep = new Departments();
        if (vo.getId() == null) {
            dep.setName(vo.getName());
            dep.setCode(vo.getCode());
            dep.setIds(vo.getIds());
            dep.setCreatePerson(LoginUtil.getLoginUserId());
            dep.setCreateTime(new Date());
            dep.setUpdateTime(new Date());
            dep.setDelFlag(0);
        } else {
            dep = departmentsService.getById(vo.getId());
            if (Objects.nonNull(vo.getDelFlag()) && vo.getDelFlag() == -1) {
                if (StringUtils.hasLength(dep.getIds())) {
                    return ResponseData.fail(500, "当前部门正在使用中");
                }
                departmentsService.removeById(vo.getId());
                return ResponseData.success("success");
            }

            SpringUtil.copyPropertiesIgnoreNull(vo, dep);
            dep.setUpdateTime(new Date());
        }
        if (departmentsService.count(new LambdaQueryWrapper<Departments>().eq(Departments::getName, vo.getName()).ne(Objects.nonNull(vo.getId()), Departments::getId, vo.getId())) > 0) {
            return ResponseData.fail(500, "部门名称重复");
        }
        if (departmentsService.count(new LambdaQueryWrapper<Departments>().eq(Departments::getCode, vo.getCode()).ne(Objects.nonNull(vo.getId()), Departments::getId, vo.getId())) > 0) {
            return ResponseData.fail(500, "部门编码重复");
        }
        departmentsService.saveOrUpdate(dep);
        return ResponseData.success("success");
    }


    @UserLoginToken
    @ApiOperation(value = "用户列表for下拉框")
    @RequestMapping(value = "user_list_o", method = RequestMethod.POST)
    public ResponseData userListO(@RequestBody NormalVo vo) {
        List<User> userList = userService.list(new QueryWrapper<User>().like(StringUtil.isNotBlank(vo.getName()), "name", vo.getName())
                .eq("state", 0)
                .eq("factory_id", LoginUtil.getLoginUserFactory()));
        return ResponseData.success(userList);
    }

    @UserLoginToken
    @ApiOperation(value = "复制权限")
    @RequestMapping(value = "copy_permissions", method = RequestMethod.POST)
    public ResponseData copyPermissions(@RequestBody CopyPermissionVo vo) {
        UserMenu um = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", vo.getId()).eq("type", vo.getType()));
        if (um == null) {
            um = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", 0).eq("type", vo.getType()));
        }
        if (StringUtil.isNotBlank(vo.getToUserId())) {
            UserMenu finalUm = um;
            Arrays.asList(vo.getToUserId().split(",")).stream().forEach(u -> {
                UserMenu umTo = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", Integer.valueOf(u)).eq("type", vo.getType()));
                if (umTo == null) {
                    umTo = new UserMenu();
                    umTo.setUserId(Integer.valueOf(u));
                    umTo.setType(vo.getType());
                }
                umTo.setMenu(finalUm.getMenu());
                userMenuService.saveOrUpdate(umTo);
            });
        }
        return ResponseData.success("success");
    }

    @ApiOperation(value = "权限判断")
    @UserLoginToken
    @RequestMapping(value = "permissions_flag", method = RequestMethod.GET)
    public ResponseData permissionsFlag(String permCode) {
        Integer userId = LoginUtil.getLoginUserId();
        UserMenu userMenu = userMenuService.getOne(new QueryWrapper<UserMenu>().eq("user_id", userId).eq("type", 0));
        if (userMenu != null && StringUtil.isNotBlank(userMenu.getMenu())) {
            JSONArray jsonArray = JSON.parseArray(userMenu.getMenu());
            List<MenuJsonVo> list = jsonArray.toJavaList(MenuJsonVo.class);
            for (MenuJsonVo l : list) {
                if (permCode.equals("home.page")) {
                    return ResponseData.success(l);
                }
                List<MenuJsonVo> listSecond = l.getSubmenu();
                if (!CollectionUtils.isEmpty(listSecond)) {
                    MenuJsonVo vo = listSecond.stream().filter(f -> f.getPermCode().equals(permCode)).findAny().orElse(null);
                    if (vo != null) {
                        return ResponseData.success(vo);
                    } else {
                        for (MenuJsonVo l2 : listSecond) {
                            List<MenuJsonVo> listThird = l2.getFiltrateConfig();
                            if (!CollectionUtils.isEmpty(listThird)) {
                                MenuJsonVo vo3 = listThird.stream().filter(f -> f.getPermCode().equals(permCode)).findAny().orElse(null);
                                if (vo3 != null) {
                                    return ResponseData.success(vo3);
                                }
                            }
                            List<MenuJsonVo> routerList = l2.getRouterMenu();
                            if (!CollectionUtils.isEmpty(routerList)) {
                                MenuJsonVo voR = routerList.stream().filter(f -> f.getPermCode().equals(permCode)).findAny().orElse(null);
                                if (voR != null) {
                                    return ResponseData.success(voR);
                                }
                            }
                        }
                    }

                }
            }
        }
        return ResponseData.fail(500, "未找到菜单" + permCode);
    }


    @ApiOperation(value = "工厂信息")
    @UserLoginToken
    @RequestMapping(value = "factory_mess", method = RequestMethod.POST)
    public ResponseData factoryMess() {
        Integer factoryId = LoginUtil.getLoginUserFactory();
        Factory factory = factoryService.getById(factoryId);
        User user = userService.getById(LoginUtil.getLoginUserId());
        factory.setCurrentMobile(user.getMobile());
        return ResponseData.success(factory);
    }

    @ApiOperation(value = "工厂信息修改")
    @UserLoginToken
    @RequestMapping(value = "factory_edit", method = RequestMethod.POST)
    public ResponseData factoryEdit(@RequestBody NormalVo vo) {
        User u = userService.getById(LoginUtil.getLoginUserId());
        if (StringUtil.isNotBlank(u.getRole())) {
            if (u.getRole().contains("1")) {
                Factory factory = factoryService.getById(LoginUtil.getLoginUserFactory());
                factory.setName(vo.getName());
                factory.setLogoUrl(vo.getLogoUrl());
                factory.setAddress(vo.getAddress());
                factoryService.updateById(factory);
            } else {
                return ResponseData.fail(500, "非管理员不可修改");
            }
        }
        return ResponseData.success("success");
    }

    @ApiOperation(value = "根据工序id获取用户列表")
    @UserLoginToken
    @PostMapping(value = "userListByProcessId")
    public ResponseData<List<User>> userListByProcessId(@RequestBody UserListByProcessIdVo userListByProcessIdVo) {
        Processes process = processesService.getByMissionId(userListByProcessIdVo.getId());
        if (Objects.isNull(process)) {
            return ResponseData.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "当前工序不存在!");
        }
        List<User> data;
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(userListByProcessIdVo.getName())) {
            userLambdaQueryWrapper.like(User::getName, userListByProcessIdVo.getName());
        }
        if (StringUtils.hasLength(process.getPermissionsName()) && !process.getPermissionsName().contains("所有人")) {
            data = userService.list(userLambdaQueryWrapper.in(User::getId, Arrays.asList(process.getPermissions().split(","))));
        } else if (StringUtils.hasLength(userListByProcessIdVo.getName())) {
            data = userService.list(userLambdaQueryWrapper);
        } else {
            data = userService.list();
        }
        return ResponseData.success(data);
    }


    @UserLoginToken
    @ApiOperation("修改权限信息")
    @PostMapping("updatePermission")
    public ResponseData<?> updatePermission(@RequestBody UpdatePermissionQuery param) {
        if (Objects.isNull(param.getUserId()) || !StringUtils.hasLength(param.getPermCode())) {
            return ResponseData.fail("必要参数不能为空!");
        }
        UserMenu userMenu = userMenuService.getOne(new LambdaQueryWrapper<UserMenu>().eq(UserMenu::getUserId, param.getUserId()).eq(UserMenu::getType, param.getType()));
        if (Objects.nonNull(userMenu) && StringUtils.hasLength(userMenu.getMenu())) {
            cn.hutool.json.JSONArray jsonArray = JSONUtil.parseArray(userMenu.getMenu());
            cn.hutool.json.JSONArray newMenu = this.updateUserMenu(jsonArray, param.getPermCode(), param.getPropertyName(), param.getPropertyValue());
            userMenu.setMenu(JSONUtil.toJsonStr(newMenu));
            userMenuService.updateById(userMenu);
        }
        return ResponseData.success(userMenu.getMenu());
    }


    @UserLoginToken
    @ApiOperation("筛选方案 分配列表下拉")
    @PostMapping("distributionUserList")
    public ResponseData<?> distributionUserList(@RequestBody(required = false) UserListByProcessIdVo query) {
        query = Optional.ofNullable(query).orElse(new UserListByProcessIdVo());
        LambdaQueryWrapper<User> userQW = new LambdaQueryWrapper<User>().like(Objects.nonNull(query.getName()), User::getName, query.getName()).eq(User::getState, 0);
        List<User> userList = userService.list(userQW);
        userList.forEach(i -> {
            i.setPassword(null);
            if (LoginUtil.getLoginUserId().equals(i.getId())) {
                i.setName("登录用户");
            }
            if (StringUtils.hasLength(i.getRole()) && i.getRole().contains("0")) {
                i.setName("系统管理员");
            }
        });
        return ResponseData.success(userList);
    }

    /**
     * 修改菜单里的值
     *
     * @param userMenuList 菜单集合
     * @param propertyName 属性名称
     * @param permCode     菜单唯一标识
     * @param newValue     修改的值
     */
    public cn.hutool.json.JSONArray updateUserMenu(cn.hutool.json.JSONArray userMenuList, String permCode, String propertyName, Object newValue) {
        cn.hutool.json.JSONArray returnDate = new cn.hutool.json.JSONArray();
        userMenuList.forEach(i -> {
            JSONObject userMenu = JSONUtil.parseObj(i);
            if (userMenu.getOrDefault("permCode", "").equals(permCode)) {
                userMenu.set(propertyName, newValue);
            }
            Object submenu = userMenu.get("submenu");
            if (Objects.nonNull(submenu) && StringUtils.hasLength(submenu.toString())) {
                cn.hutool.json.JSONArray submenuArray = JSONUtil.parseArray(submenu);
                cn.hutool.json.JSONArray jsonArray = this.updateUserMenu(submenuArray, permCode, propertyName, newValue);
                userMenu.remove("submenu");
                userMenu.putOnce("submenu", jsonArray);
            }
            Object routerMenu = userMenu.get("routerMenu");
            if (Objects.nonNull(routerMenu) && StringUtils.hasLength(routerMenu.toString())) {
                cn.hutool.json.JSONArray routerMenuArray = JSONUtil.parseArray(routerMenu);
                cn.hutool.json.JSONArray jsonArray = this.updateUserMenu(routerMenuArray, permCode, propertyName, newValue);
                userMenu.remove("routerMenu");
                userMenu.putOnce("routerMenu", jsonArray);
            }
            returnDate.add(userMenu);
        });
        return returnDate;
    }
}
